package com.ruoyi.market.service.impl;

import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.market.domain.VerCoupon;
import com.ruoyi.market.domain.VerUserCouponOrderRelate;
import com.ruoyi.market.domain.dto.*;
import com.ruoyi.market.domain.vo.PageVo;
import com.ruoyi.market.domain.vo.PaginationVo;
import com.ruoyi.market.mapper.VerCouponMapper;
import com.ruoyi.market.service.IVerCouponService;
import com.ruoyi.product.domain.ProductSkuVo;
import com.ruoyi.product.domain.vo.Activity;
import com.ruoyi.product.domain.vo.Coupon;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 优惠券Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-02
 */
@Service
public class VerCouponServiceImpl implements IVerCouponService {
    @Autowired
    private VerCouponMapper verCouponMapper;

    /**
     * 查询优惠券
     *
     * @param id 优惠券主键
     * @return 优惠券
     */
    @Override
    public VerCoupon selectVerCouponById(Long id) {
        return verCouponMapper.selectVerCouponById(id);
    }

    /**
     * 查询优惠券列表
     *
     * @param verCoupon 优惠券
     * @return 优惠券
     */
    @Override
    public List<VerCoupon> selectVerCouponList(VerCoupon verCoupon) {
        return verCouponMapper.selectVerCouponList(verCoupon);
    }

    /**
     * 新增优惠券
     *
     * @param verCoupon 优惠券
     * @return 结果
     */
    @Override
    public int insertVerCoupon(VerCoupon verCoupon) {
        return verCouponMapper.insertVerCoupon(verCoupon);
    }

    /**
     * 修改优惠券
     *
     * @param verCoupon 优惠券
     * @return 结果
     */
    @Override
    public int updateVerCoupon(VerCoupon verCoupon) {
        return verCouponMapper.updateVerCoupon(verCoupon);
    }

    /**
     * 批量删除优惠券
     *
     * @param ids 需要删除的优惠券主键
     * @return 结果
     */
    @Override
    public int deleteVerCouponByIds(Long[] ids) {
        return verCouponMapper.deleteVerCouponByIds(ids);
    }

    /**
     * 删除优惠券信息
     *
     * @param id 优惠券主键
     * @return 结果
     */
    @Override
    public int deleteVerCouponById(Long id) {
        return verCouponMapper.deleteVerCouponById(id);
    }

    /**
     * 获取优惠券组商品列表
     *
     * @param couponGroupDto
     */
    @Override
    public List<CouponGroupDto> couponGroupList(CouponGroupDto couponGroupDto) {
        List<CouponGroupDto> result = verCouponMapper.couponGroupList(couponGroupDto);

        // 处理URLs字段，将逗号分隔的字符串转换为List
        if (result != null) {
            for (CouponGroupDto group : result) {
                if (group.getCoupons() != null) {
                    for (CouponDto coupon : group.getCoupons()) {
                        if (coupon.getSkus() != null) {
                            for (ProductSkuVo sku : coupon.getSkus()) {
                                // 处理URLs字段，将逗号分隔的字符串转换为List
                                if (sku.getUrl() != null && !sku.getUrl().trim().isEmpty()) {
                                    sku.setUrls(Arrays.asList(sku.getUrl().split(",")));
                                }
                                // 去除双斜杠
                                sku.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(sku.getSpecNameGroupRaw()));
                                sku.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(sku.getSpecValueGroupRaw()));

                            }
                        }
                    }
                }

            }
        }
        return result;
    }

    /**
     * 获取用户优惠券列表
     *
     * @param userId
     */
    @Override
    public List<userCouponDto> userCouponList(Long userId) {
        return verCouponMapper.userCouponList(userId);
    }

    /**
     * 获取用户优惠券使用明细表
     *
     * @param userId
     */
    @Override
    public List<VerUserCouponDto> getUserCouponDetail(Long userId) {
        return verCouponMapper.getuserCouponDetail(userId);
    }

    /**
     * 获取优惠券销量前8的商品
     *
     * @param couponId 优惠券ID
     * @return 商品列表
     */
    @Override
    public List<SkuCouponsDto> getCouponSaleTop8(Long couponId) {
        List<SkuCouponsDto> rawResult = verCouponMapper.getCouponSaleTop8(couponId);

        if (rawResult == null || rawResult.isEmpty()) {
            return new ArrayList<>();
        }

        // 按skuId分组，合并相同skuId的urls
        Map<Long, SkuCouponsDto> skuMap = new LinkedHashMap<>();
        Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
        Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
        Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

        for (SkuCouponsDto item : rawResult) {
            Long skuId = item.getSkuId();

            // 如果该skuId还没有处理过，创建新的对象
            if (!skuMap.containsKey(skuId)) {
                SkuCouponsDto mergedItem = new SkuCouponsDto();
                // 复制基本信息
                mergedItem.setSkuId(item.getSkuId());
                mergedItem.setSpuId(item.getSpuId());
                mergedItem.setCode(item.getCode());
                mergedItem.setCategoryId(item.getCategoryId());
                mergedItem.setSalesVolume(item.getSalesVolume());
                mergedItem.setSpecData(item.getSpecData());
                mergedItem.setPrice(item.getPrice());
                mergedItem.setOriginalPrice(item.getOriginalPrice());
                mergedItem.setStock(item.getStock());
                mergedItem.setLowStock(item.getLowStock());
                mergedItem.setWeight(item.getWeight());
                mergedItem.setVolume(item.getVolume());
                mergedItem.setStatus(item.getStatus());
                mergedItem.setSpecNameGroupRaw(item.getSpecNameGroupRaw());
                mergedItem.setSpecValueGroupRaw(item.getSpecValueGroupRaw());
                mergedItem.setCreatedAt(item.getCreatedAt());
                mergedItem.setUpdatedAt(item.getUpdatedAt());
                mergedItem.setSkuName(item.getSkuName());
                mergedItem.setDescription(item.getDescription());
                mergedItem.setCouponId(item.getCouponId());
                mergedItem.setActivityId(item.getActivityId());

                // 复制优惠券信息
                mergedItem.setCouponCode(item.getCouponCode());
                mergedItem.setCouponType(item.getCouponType());
                mergedItem.setCouponValue(item.getCouponValue());
                mergedItem.setCouponMinAmount(item.getCouponMinAmount());
                mergedItem.setCouponStartTime(item.getCouponStartTime());
                mergedItem.setCouponEndTime(item.getCouponEndTime());

                // 复制活动信息
                mergedItem.setActivityName(item.getActivityName());
                mergedItem.setActivityType(item.getActivityType());
                mergedItem.setActivityStatus(item.getActivityStatus());
                mergedItem.setActivityDescription(item.getActivityDescription());
                mergedItem.setActivityEndTime(item.getActivityEndTime());
                mergedItem.setActivityCreateTime(item.getActivityCreateTime());

                skuMap.put(skuId, mergedItem);
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());
            }

            // 收集URLs
            if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                String[] urls = item.getUrlRaw().split(",");
                for (String url : urls) {
                    String trimmedUrl = url.trim();
                    if (!trimmedUrl.isEmpty()) {
                        skuUrlsMap.get(skuId).add(trimmedUrl);
                    }
                }
            }

            // 收集活动信息
            if (item.getActivityId() != null) {
                Activity activity = new Activity();
                activity.setActivityId(item.getActivityId());
                activity.setActivityName(item.getActivityName());
                activity.setActivityType(item.getActivityType());
                activity.setActivityStatus(item.getActivityStatus());
                activity.setActivityDescription(item.getActivityDescription());
                activity.setActivityEndTime(item.getActivityEndTime());
                activity.setActivityCreateTime(item.getActivityCreateTime());

                // 避免重复添加相同的活动
                List<Activity> activities = skuActivitiesMap.get(skuId);
                boolean exists = activities.stream()
                        .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                if (!exists) {
                    activities.add(activity);
                }
            }

            // 收集优惠券信息
            if (item.getCouponId() != null) {
                Coupon coupon = new Coupon();
                coupon.setCouponId(item.getCouponId());
                coupon.setCouponCode(item.getCouponCode());
                coupon.setCouponType(item.getCouponType());
                coupon.setCouponValue(item.getCouponValue());
                coupon.setCouponMinAmount(item.getCouponMinAmount());
                coupon.setCouponStartTime(item.getCouponStartTime());
                coupon.setCouponEndTime(item.getCouponEndTime());

                // 避免重复添加相同的优惠券
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                boolean exists = coupons.stream()
                        .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                if (!exists) {
                    coupons.add(coupon);
                }
            }
        }

        // 处理最终结果
        List<SkuCouponsDto> result = new ArrayList<>();
        for (SkuCouponsDto item : skuMap.values()) {
            Long skuId = item.getSkuId();

            // 设置合并后的URLs
            Set<String> urlSet = skuUrlsMap.get(skuId);
            if (!urlSet.isEmpty()) {
                item.setUrls(new ArrayList<>(urlSet));
            }

            // 处理规格组数据，去除双斜杠
            item.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
            item.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));

            // 设置活动列表
            List<Activity> activities = skuActivitiesMap.get(skuId);
            if (!activities.isEmpty()) {
                item.setActivityList(activities);
            }

            // 设置优惠券列表
            List<Coupon> coupons = skuCouponsMap.get(skuId);
            if (!coupons.isEmpty()) {
                item.setCouponList(coupons);
            }

            result.add(item);
        }

        // 按销量降序排序，并只返回前8条数据
        result.sort((a, b) -> {
            Long salesA = a.getSalesVolume() != null ? a.getSalesVolume() : 0L;
            Long salesB = b.getSalesVolume() != null ? b.getSalesVolume() : 0L;
            return salesB.compareTo(salesA); // 降序排序
        });

        // 限制为前8条数据
        if (result.size() > 8) {
            result = result.subList(0, 8);
        }

        return result;
    }

    /**
     * 根据优惠券id获取销量最高的商品（支持分页）
     *
     * @param couponId   优惠券ID
     * @param pagination 分页信息
     * @return 商品列表
     */
    @Override
    public List<SkuCouponsDto> getCouponSaleTop8(Long couponId, PaginationVo pagination) {
        List<SkuCouponsDto> rawResult = verCouponMapper.getCouponSaleTop8(couponId);

        if (rawResult == null || rawResult.isEmpty()) {
            return new ArrayList<>();
        }

        // 按skuId分组，合并相同skuId的urls
        Map<Long, SkuCouponsDto> skuMap = new LinkedHashMap<>();
        Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
        Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
        Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

        for (SkuCouponsDto item : rawResult) {
            Long skuId = item.getSkuId();

            // 如果该skuId还没有处理过，创建新的对象
            if (!skuMap.containsKey(skuId)) {
                SkuCouponsDto mergedItem = new SkuCouponsDto();
                BeanUtils.copyProperties(item, mergedItem);
                skuMap.put(skuId, mergedItem);
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());
            }

            // 收集URLs
            if (item.getUrls() != null && !item.getUrls().isEmpty()) {
                skuUrlsMap.get(skuId).addAll(item.getUrls());
            }

            // 收集活动信息
            if (item.getActivityList() != null && !item.getActivityList().isEmpty()) {
                for (Activity activity : item.getActivityList()) {
                    boolean exists = skuActivitiesMap.get(skuId).stream()
                            .anyMatch(existingActivity -> existingActivity.getActivityId()
                                    .equals(activity.getActivityId()));
                    if (!exists) {
                        skuActivitiesMap.get(skuId).add(activity);
                    }
                }
            }

            // 收集优惠券信息
            if (item.getCouponList() != null && !item.getCouponList().isEmpty()) {
                for (Coupon coupon : item.getCouponList()) {
                    boolean exists = skuCouponsMap.get(skuId).stream()
                            .anyMatch(existingCoupon -> existingCoupon.getId().equals(coupon.getId()));
                    if (!exists) {
                        skuCouponsMap.get(skuId).add(coupon);
                    }
                }
            }
        }

        // 处理最终结果
        List<SkuCouponsDto> result = new ArrayList<>();
        for (SkuCouponsDto item : skuMap.values()) {
            Long skuId = item.getSkuId();

            // 设置合并后的URLs
            Set<String> urlSet = skuUrlsMap.get(skuId);
            if (!urlSet.isEmpty()) {
                item.setUrls(new ArrayList<>(urlSet));
            }

            // 处理规格组数据，去除双斜杠
            item.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
            item.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));

            // 设置活动列表
            List<Activity> activities = skuActivitiesMap.get(skuId);
            if (!activities.isEmpty()) {
                item.setActivityList(activities);
            }

            // 设置优惠券列表
            List<Coupon> coupons = skuCouponsMap.get(skuId);
            if (!coupons.isEmpty()) {
                item.setCouponList(coupons);
            }

            result.add(item);
        }

        // 按销量降序排序
        result.sort((a, b) -> {
            Long salesA = a.getSalesVolume() != null ? a.getSalesVolume() : 0L;
            Long salesB = b.getSalesVolume() != null ? b.getSalesVolume() : 0L;
            return salesB.compareTo(salesA); // 降序排序
        });

        // 应用分页
        if (pagination != null && pagination.getPageNum() != null && pagination.getPageSize() != null) {
            int pageNum = pagination.getPageNum();
            int pageSize = pagination.getPageSize();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, result.size());

            if (startIndex < result.size()) {
                result = result.subList(startIndex, endIndex);
            } else {
                result = new ArrayList<>();
            }
        }

        return result;
    }

    /**
     * 根据优惠券id获取销量最高的商品（支持分页，返回分页信息）
     *
     * @param couponId   优惠券ID
     * @param pagination 分页信息
     * @return 包含数据和分页信息的响应对象
     */
    @Override
    public CouponSaleTopResponseDto getCouponSaleTop8WithPagination(Long couponId, PaginationVo pagination) {
        // 先获取所有数据（不分页）来计算总数
        List<SkuCouponsDto> allData = getCouponSaleTop8(couponId, null);

        // 计算总数
        long total = allData.size();

        // 应用分页
        List<SkuCouponsDto> pagedData;
        if (pagination != null && pagination.getPageNum() != null && pagination.getPageSize() != null) {
            int pageNum = pagination.getPageNum();
            int pageSize = pagination.getPageSize();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allData.size());

            if (startIndex < allData.size()) {
                pagedData = allData.subList(startIndex, endIndex);
            } else {
                pagedData = new ArrayList<>();
            }
        } else {
            pagedData = allData;
        }

        // 创建分页信息
        PageVo pageVo = new PageVo();
        pageVo.setTotal(total);
        pageVo.setPageNum(
                pagination != null && pagination.getPageNum() != null ? pagination.getPageNum().longValue() : 1L);
        pageVo.setPageSize(pagination != null && pagination.getPageSize() != null ? pagination.getPageSize().longValue()
                : (long) pagedData.size());

        // 创建响应对象
        CouponSaleTopResponseDto response = new CouponSaleTopResponseDto();
        response.setData(pagedData);
        response.setPagination(pageVo);

        return response;
    }

    /**
     * 根据优惠券id获取分类商品列表
     *
     * @param couponId
     */
    @Override
    public List<SkuCouponsCategoryDto> getCouponCategoryList(Long couponId) {
        // 获取原始数据
        List<SkuCouponsCategoryDto> rawData = verCouponMapper.getCouponCategoryList(couponId);

        // 按categoryId和categoryName分组
        Map<String, List<SkuCouponsCategoryDto>> groupedData = rawData.stream()
                .collect(Collectors.groupingBy(item -> item.getCategoryId() + "_" + item.getCategoryName()));

        List<SkuCouponsCategoryDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoryDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoryDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoryDto categoryDto = new SkuCouponsCategoryDto();
            SkuCouponsCategoryDto firstItem = categoryItems.get(0);
            categoryDto.setCategoryId(firstItem.getCategoryId());
            categoryDto.setCategoryName(firstItem.getCategoryName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoryDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoryDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoryDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoryDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoryDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setCategoryId(String.valueOf(firstSkuItem.getCategoryId()));
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoryDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息（这里可以根据需要设置）
            List<PageVo> pagination = new ArrayList<>();
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size());
            pageVo.setPageNum(1L);
            pageVo.setPageSize(8L);
            pagination.add(pageVo);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        return result;
    }

    /**
     * 根据优惠券id获取分类商品列表（分页）
     *
     * @param request 请求参数，包含优惠券ID、分类ID和分页信息
     */
    @Override
    public List<SkuCouponsCategoryDto> getCouponCategoryListPage(SkuCouponsCategoryRequestDto request) {
        // 计算offset值
        if (request.getPagination() != null && request.getPagination().getPageNum() != null
                && request.getPagination().getPageSize() != null) {
            int offset = (request.getPagination().getPageNum() - 1) * request.getPagination().getPageSize();
            request.setOffset(offset);
        }

        // 获取原始数据
        List<SkuCouponsCategoryDto> rawData = verCouponMapper.getCouponCategoryListPage(request);

        // 按categoryId和categoryName分组
        Map<String, List<SkuCouponsCategoryDto>> groupedData = rawData.stream()
                .collect(Collectors.groupingBy(item -> item.getCategoryId() + "_" + item.getCategoryName()));

        List<SkuCouponsCategoryDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoryDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoryDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoryDto categoryDto = new SkuCouponsCategoryDto();
            SkuCouponsCategoryDto firstItem = categoryItems.get(0);
            categoryDto.setCategoryId(firstItem.getCategoryId());
            categoryDto.setCategoryName(firstItem.getCategoryName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoryDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoryDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoryDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoryDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoryDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setCategoryId(String.valueOf(firstSkuItem.getCategoryId()));
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoryDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息
            List<PageVo> pagination = new ArrayList<>();
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size());
            pageVo.setPageNum(request.getPagination() != null ? request.getPagination().getPageNum().longValue() : 1L);
            pageVo.setPageSize(
                    request.getPagination() != null ? request.getPagination().getPageSize().longValue() : 8L);
            pagination.add(pageVo);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        return result;
    }

    /**
     * 获取所有优惠券
     */
    @Override
    public List<CouponGroupResponseDto> getAllCoupons() {
        List<CouponGroupFlatDto> rawData = verCouponMapper.getAllCoupons();

        Map<Long, List<CouponGroupFlatDto>> groupedData = rawData.stream()
                .filter(item -> item.getCouponGroupId() != null)
                .collect(Collectors.groupingBy(CouponGroupFlatDto::getCouponGroupId));

        List<CouponGroupResponseDto> result = new ArrayList<>();
        for (Map.Entry<Long, List<CouponGroupFlatDto>> entry : groupedData.entrySet()) {
            Long groupId = entry.getKey();
            List<CouponGroupFlatDto> groupItems = entry.getValue();

            if (!groupItems.isEmpty()) {
                CouponGroupResponseDto groupResponse = new CouponGroupResponseDto();
                groupResponse.setCouponGroupId(groupId);
                groupResponse.setCouponName(groupItems.get(0).getCouponGroupName());

                List<CouponResponseDto> couponList = groupItems.stream()
                        .filter(item -> item.getCouponId() != null) // Only include rows with actual coupon data
                        .map(item -> {
                            CouponResponseDto responseDto = new CouponResponseDto();
                            responseDto.setCouponsId(item.getCouponId());
                            responseDto.setName(item.getCouponName());
                            responseDto.setCode(item.getCouponCode());
                            responseDto.setType(item.getCouponType());
                            responseDto.setValue(item.getCouponValue());
                            responseDto.setMinAmount(item.getCouponMinAmount());
                            responseDto.setStartTime(item.getCouponStartTime());
                            responseDto.setEndTime(item.getCouponEndTime());
                            return responseDto;
                        })
                        .collect(Collectors.toList());

                groupResponse.setCouponList(couponList);
                result.add(groupResponse);
            }
        }

        return result;
    }

    @Override
    public List<SkuCouponsDto> getAllCouponsSaleTop8() {
        List<SkuCouponsDto> rawResult = verCouponMapper.getAllCouponsSaleTop8();

        if (rawResult == null || rawResult.isEmpty()) {
            return new ArrayList<>();
        }

        // 按skuId分组，合并相同skuId的urls
        Map<Long, SkuCouponsDto> skuMap = new LinkedHashMap<>();
        Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
        Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
        Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

        for (SkuCouponsDto item : rawResult) {
            Long skuId = item.getSkuId();

            // 如果该skuId还没有处理过，创建新的对象
            if (!skuMap.containsKey(skuId)) {
                SkuCouponsDto mergedItem = new SkuCouponsDto();
                // 复制基本信息
                mergedItem.setSkuId(item.getSkuId());
                mergedItem.setSpuId(item.getSpuId());
                mergedItem.setCode(item.getCode());
                mergedItem.setCategoryId(item.getCategoryId());
                mergedItem.setSalesVolume(item.getSalesVolume());
                mergedItem.setSpecData(item.getSpecData());
                mergedItem.setPrice(item.getPrice());
                mergedItem.setOriginalPrice(item.getOriginalPrice());
                mergedItem.setStock(item.getStock());
                mergedItem.setLowStock(item.getLowStock());
                mergedItem.setWeight(item.getWeight());
                mergedItem.setVolume(item.getVolume());
                mergedItem.setStatus(item.getStatus());
                mergedItem.setSpecNameGroupRaw(item.getSpecNameGroupRaw());
                mergedItem.setSpecValueGroupRaw(item.getSpecValueGroupRaw());
                mergedItem.setCreatedAt(item.getCreatedAt());
                mergedItem.setUpdatedAt(item.getUpdatedAt());
                mergedItem.setSkuName(item.getSkuName());
                mergedItem.setDescription(item.getDescription());
                mergedItem.setCouponId(item.getCouponId());
                mergedItem.setActivityId(item.getActivityId());

                // 复制优惠券信息
                mergedItem.setCouponCode(item.getCouponCode());
                mergedItem.setCouponType(item.getCouponType());
                mergedItem.setCouponValue(item.getCouponValue());
                mergedItem.setCouponMinAmount(item.getCouponMinAmount());
                mergedItem.setCouponStartTime(item.getCouponStartTime());
                mergedItem.setCouponEndTime(item.getCouponEndTime());

                // 复制活动信息
                mergedItem.setActivityName(item.getActivityName());
                mergedItem.setActivityType(item.getActivityType());
                mergedItem.setActivityStatus(item.getActivityStatus());
                mergedItem.setActivityDescription(item.getActivityDescription());
                mergedItem.setActivityEndTime(item.getActivityEndTime());
                mergedItem.setActivityCreateTime(item.getActivityCreateTime());

                skuMap.put(skuId, mergedItem);
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());
            }

            // 收集URLs
            if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                String[] urls = item.getUrlRaw().split(",");
                for (String url : urls) {
                    String trimmedUrl = url.trim();
                    if (!trimmedUrl.isEmpty()) {
                        skuUrlsMap.get(skuId).add(trimmedUrl);
                    }
                }
            }

            // 收集活动信息
            if (item.getActivityId() != null) {
                Activity activity = new Activity();
                activity.setActivityId(item.getActivityId());
                activity.setActivityName(item.getActivityName());
                activity.setActivityType(item.getActivityType());
                activity.setActivityStatus(item.getActivityStatus());
                activity.setActivityDescription(item.getActivityDescription());
                activity.setActivityEndTime(item.getActivityEndTime());
                activity.setActivityCreateTime(item.getActivityCreateTime());

                // 避免重复添加相同的活动
                List<Activity> activities = skuActivitiesMap.get(skuId);
                boolean exists = activities.stream()
                        .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                if (!exists) {
                    activities.add(activity);
                }
            }

            // 收集优惠券信息
            if (item.getCouponId() != null) {
                Coupon coupon = new Coupon();
                coupon.setCouponId(item.getCouponId());
                coupon.setCouponCode(item.getCouponCode());
                coupon.setCouponType(item.getCouponType());
                coupon.setCouponValue(item.getCouponValue());
                coupon.setCouponMinAmount(item.getCouponMinAmount());
                coupon.setCouponStartTime(item.getCouponStartTime());
                coupon.setCouponEndTime(item.getCouponEndTime());

                // 避免重复添加相同的优惠券
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                boolean exists = coupons.stream()
                        .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                if (!exists) {
                    coupons.add(coupon);
                }
            }
        }

        // 处理最终结果
        List<SkuCouponsDto> result = new ArrayList<>();
        for (SkuCouponsDto item : skuMap.values()) {
            Long skuId = item.getSkuId();

            // 设置合并后的URLs
            Set<String> urlSet = skuUrlsMap.get(skuId);
            if (!urlSet.isEmpty()) {
                item.setUrls(new ArrayList<>(urlSet));
            }

            // 处理规格组数据，去除双斜杠
            item.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
            item.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));

            // 设置活动列表
            List<Activity> activities = skuActivitiesMap.get(skuId);
            if (!activities.isEmpty()) {
                item.setActivityList(activities);
            }

            // 设置优惠券列表
            List<Coupon> coupons = skuCouponsMap.get(skuId);
            if (!coupons.isEmpty()) {
                item.setCouponList(coupons);
            }

            result.add(item);
        }

        // 按销量降序排序，并只返回前8条数据
        result.sort((a, b) -> {
            Long salesA = a.getSalesVolume() != null ? a.getSalesVolume() : 0L;
            Long salesB = b.getSalesVolume() != null ? b.getSalesVolume() : 0L;
            return salesB.compareTo(salesA); // 降序排序
        });

        // 限制为前8条数据
        if (result.size() > 8) {
            result = result.subList(0, 8);
        }

        return result;
    }

    /**
     * 获取所有优惠券销量最高的商品（支持分页，返回分页信息）
     *
     * @param pagination 分页信息
     * @return 包含数据和分页信息的响应对象
     */
    @Override
    public AllCouponsSaleTopResponseDto getAllCouponsSaleTop8WithPagination(PaginationVo pagination) {
        // 先获取所有数据（不分页）来计算总数
        List<SkuCouponsDto> allData = getAllCouponsSaleTop8();

        // 计算总数
        long total = allData.size();

        // 应用分页
        List<SkuCouponsDto> pagedData;
        if (pagination != null && pagination.getPageNum() != null && pagination.getPageSize() != null) {
            int pageNum = pagination.getPageNum();
            int pageSize = pagination.getPageSize();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allData.size());

            if (startIndex < allData.size()) {
                pagedData = allData.subList(startIndex, endIndex);
            } else {
                pagedData = new ArrayList<>();
            }
        } else {
            pagedData = allData;
        }

        // 创建分页信息
        PageVo pageVo = new PageVo();
        pageVo.setTotal(total);
        pageVo.setPageNum(
                pagination != null && pagination.getPageNum() != null ? pagination.getPageNum().longValue() : 1L);
        pageVo.setPageSize(pagination != null && pagination.getPageSize() != null ? pagination.getPageSize().longValue()
                : (long) pagedData.size());

        // 创建响应对象
        AllCouponsSaleTopResponseDto response = new AllCouponsSaleTopResponseDto();
        response.setData(pagedData);
        response.setPagination(pageVo);

        return response;
    }

    /**
     * 获取所有优惠券组分类商品列表
     *
     * @return 优惠券组分类商品列表
     */
    @Override
    public List<SkuCouponsCategoriesDto> getAllCouponGroupCategorySkus() {
        // 获取原始数据
        List<SkuCouponsCategoriesDto> rawData = verCouponMapper.getAllCouponGroupCategorySkus();

        // 过滤掉无效数据
        List<SkuCouponsCategoriesDto> filteredData = rawData.stream()
                .filter(item -> item.getCouponGroupId() != null
                        && item.getCouponGroupName() != null
                        && !item.getCouponGroupName().trim().isEmpty()
                        && item.getSkuId() != null
                        && item.getCouponId() != null)
                .collect(Collectors.toList());

        // 按couponGroupId和couponGroupName分组
        Map<String, List<SkuCouponsCategoriesDto>> groupedData = filteredData.stream()
                .collect(Collectors.groupingBy(item -> item.getCouponGroupId() + "_" + item.getCouponGroupName()));

        List<SkuCouponsCategoriesDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoriesDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoriesDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoriesDto categoryDto = new SkuCouponsCategoriesDto();
            SkuCouponsCategoriesDto firstItem = categoryItems.get(0);
            categoryDto.setCouponGroupId(firstItem.getCouponGroupId());
            categoryDto.setCouponGroupName(firstItem.getCouponGroupName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoriesDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoriesDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoriesDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoriesDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoriesDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoriesDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // Set additional fields to match expected output format
                        activity.setType(item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setValue(0.0); // Default value, can be set from database if available
                        activity.setMinAmount(0.0); // Default value, can be set from database if available
                        activity.setStartTime(item.getActivityStartTime());
                        activity.setEndTime(item.getActivityEndTime());
                        activity.setActivityDesc(item.getActivityDescription());
                        activity.setPosterUrl(item.getPosterUrl());
                        activity.setCreateTime(item.getActivityCreateTime());
                        activity.setUpdateTime(item.getActivityCreateTime()); // Use create time as update time if not
                                                                              // available

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // Set additional fields to match expected output format
                        coupon.setCode(item.getCouponCode());
                        coupon.setCouponGroupId(null); // Set from database if available
                        coupon.setCouponStock(item.getCouponStock());
                        coupon.setCreateBy(null); // Set from database if available
                        coupon.setCreateTime(null); // Set from database if available
                        coupon.setEndTime(item.getCouponEndTime());
                        coupon.setGetTime(item.getGetTime());
                        coupon.setId(item.getCouponId());
                        coupon.setMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setName(item.getCouponName());
                        coupon.setRemark(item.getCouponRemark());
                        coupon.setStartTime(item.getCouponStartTime());
                        coupon.setStatus(item.getCouponStatus() != null ? item.getCouponStatus().longValue() : null);
                        coupon.setType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setUpdateBy(null); // Set from database if available
                        coupon.setUpdateTime(null); // Set from database if available
                        coupon.setUseOrderId(null); // Set from database if available
                        coupon.setUserId(null); // Set from database if available
                        coupon.setValue(item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            // 设置所有SKU数据，不进行分页限制
            categoryDto.setSkus(skuList);

            // 设置分页信息（显示总数，但实际返回所有数据）
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size()); // 该分类下的商品总数
            pageVo.setPageNum(1L); // 当前页数
            pageVo.setPageSize((long) skuList.size()); // 每页条数等于总数（表示返回所有数据）
            categoryDto.setPagination(Arrays.asList(pageVo));

            result.add(categoryDto);
        }

        // 按照couponGroupId排序
        result.sort((a, b) -> {
            Long groupIdA = a.getCouponGroupId() != null ? a.getCouponGroupId() : 0L;
            Long groupIdB = b.getCouponGroupId() != null ? b.getCouponGroupId() : 0L;
            return groupIdA.compareTo(groupIdB);
        });

        return result;
    }

    /**
     * 根据优惠券组id获取不同页数的商品记录
     *
     * @param request 请求参数，包含优惠券组ID和分页信息
     */
    @Override
    public List<SkuCouponsCategoryDto> getCouponGroupPage(CouponGroupPageRequestDto request) {
        // 计算offset值
        if (request.getPagination() != null && request.getPagination().getPageNum() != null
                && request.getPagination().getPageSize() != null) {
            int offset = (request.getPagination().getPageNum() - 1) * request.getPagination().getPageSize();
            request.setOffset(offset);
        }

        // 获取原始数据
        List<SkuCouponsCategoryDto> rawData = verCouponMapper.getCouponGroupPage(request);

        // 按categoryId和categoryName分组
        Map<String, List<SkuCouponsCategoryDto>> groupedData = rawData.stream()
                .collect(Collectors.groupingBy(item -> item.getCategoryId() + "_" + item.getCategoryName()));

        List<SkuCouponsCategoryDto> result = new ArrayList<>();

        for (Map.Entry<String, List<SkuCouponsCategoryDto>> entry : groupedData.entrySet()) {
            List<SkuCouponsCategoryDto> categoryItems = entry.getValue();
            if (categoryItems.isEmpty())
                continue;

            // 创建分类DTO
            SkuCouponsCategoryDto categoryDto = new SkuCouponsCategoryDto();
            SkuCouponsCategoryDto firstItem = categoryItems.get(0);
            categoryDto.setCategoryId(firstItem.getCategoryId());
            categoryDto.setCategoryName(firstItem.getCategoryName());

            // 按skuId分组，构建SKU列表
            Map<Long, List<SkuCouponsCategoryDto>> skuGroups = categoryItems.stream()
                    .collect(Collectors.groupingBy(SkuCouponsCategoryDto::getSkuId));

            // 用于收集每个SKU的URLs
            Map<Long, Set<String>> skuUrlsMap = new HashMap<>();
            Map<Long, List<Activity>> skuActivitiesMap = new HashMap<>();
            Map<Long, List<Coupon>> skuCouponsMap = new HashMap<>();

            List<SkuCouponsDto> skuList = new ArrayList<>();
            for (Map.Entry<Long, List<SkuCouponsCategoryDto>> skuEntry : skuGroups.entrySet()) {
                List<SkuCouponsCategoryDto> skuItems = skuEntry.getValue();
                if (skuItems.isEmpty())
                    continue;

                SkuCouponsCategoryDto firstSkuItem = skuItems.get(0);
                Long skuId = firstSkuItem.getSkuId();

                // 初始化收集器
                skuUrlsMap.put(skuId, new HashSet<>());
                skuActivitiesMap.put(skuId, new ArrayList<>());
                skuCouponsMap.put(skuId, new ArrayList<>());

                // 构建SKU DTO
                SkuCouponsDto skuDto = new SkuCouponsDto();
                skuDto.setSkuId(firstSkuItem.getSkuId());
                skuDto.setSpuId(firstSkuItem.getSpuId());
                skuDto.setCode(firstSkuItem.getCode());
                skuDto.setCategoryId(String.valueOf(firstSkuItem.getCategoryId()));
                skuDto.setSpecData(firstSkuItem.getSpecData());
                skuDto.setPrice(firstSkuItem.getPrice());
                skuDto.setOriginalPrice(firstSkuItem.getOriginalPrice());
                skuDto.setSkuName(firstSkuItem.getSkuName());
                skuDto.setDescription(firstSkuItem.getDescription());
                skuDto.setStock(firstSkuItem.getStock());
                skuDto.setSalesVolume(firstSkuItem.getSalesVolume());
                skuDto.setLowStock(firstSkuItem.getLowStock());
                skuDto.setWeight(firstSkuItem.getWeight());
                skuDto.setVolume(firstSkuItem.getVolume());
                skuDto.setStatus(firstSkuItem.getStatus() != null ? firstSkuItem.getStatus().longValue() : null);
                skuDto.setCreatedAt(firstSkuItem.getCreatedAt());
                skuDto.setUpdatedAt(firstSkuItem.getUpdatedAt());
                skuDto.setUrlRaw(firstSkuItem.getUrlRaw());

                // 处理规格组数据，使用SpecGroupUtils处理
                skuDto.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(firstSkuItem.getSpecNameGroupRaw()));
                skuDto.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(firstSkuItem.getSpecValueGroupRaw()));

                // 收集URLs、活动和优惠券信息
                for (SkuCouponsCategoryDto item : skuItems) {
                    // 收集URLs
                    if (item.getUrlRaw() != null && !item.getUrlRaw().trim().isEmpty()) {
                        String[] urls = item.getUrlRaw().split(",");
                        for (String url : urls) {
                            String trimmedUrl = url.trim();
                            if (!trimmedUrl.isEmpty()) {
                                skuUrlsMap.get(skuId).add(trimmedUrl);
                            }
                        }
                    }

                    // 收集活动信息
                    if (item.getActivityId() != null) {
                        Activity activity = new Activity();
                        activity.setActivityId(item.getActivityId());
                        activity.setActivityName(item.getActivityName());
                        activity.setActivityType(
                                item.getActivityType() != null ? item.getActivityType().longValue() : null);
                        activity.setActivityStatus(
                                item.getActivityStatus() != null ? item.getActivityStatus().longValue() : null);
                        activity.setActivityDescription(item.getActivityDescription());
                        activity.setActivityEndTime(item.getActivityEndTime());
                        activity.setActivityCreateTime(item.getActivityCreateTime());

                        // 避免重复添加相同的活动
                        List<Activity> activities = skuActivitiesMap.get(skuId);
                        boolean exists = activities.stream()
                                .anyMatch(a -> a.getActivityId().equals(activity.getActivityId()));
                        if (!exists) {
                            activities.add(activity);
                        }
                    }

                    // 收集优惠券信息
                    if (item.getCouponId() != null) {
                        Coupon coupon = new Coupon();
                        coupon.setCouponId(item.getCouponId());
                        coupon.setCouponCode(item.getCouponCode());
                        coupon.setCouponType(item.getCouponType() != null ? item.getCouponType().longValue() : null);
                        coupon.setCouponValue(
                                item.getCouponValue() != null ? item.getCouponValue().doubleValue() : null);
                        coupon.setCouponMinAmount(
                                item.getCouponMinAmount() != null ? item.getCouponMinAmount().doubleValue() : null);
                        coupon.setCouponStartTime(
                                item.getCouponStartTime() != null ? item.getCouponStartTime().toString() : null);
                        coupon.setCouponEndTime(
                                item.getCouponEndTime() != null ? item.getCouponEndTime().toString() : null);

                        // 避免重复添加相同的优惠券
                        List<Coupon> coupons = skuCouponsMap.get(skuId);
                        boolean exists = coupons.stream()
                                .anyMatch(c -> c.getCouponId().equals(coupon.getCouponId()));
                        if (!exists) {
                            coupons.add(coupon);
                        }
                    }
                }

                // 设置合并后的URLs
                Set<String> urlSet = skuUrlsMap.get(skuId);
                if (!urlSet.isEmpty()) {
                    skuDto.setUrls(new ArrayList<>(urlSet));
                }

                // 设置活动列表
                List<Activity> activities = skuActivitiesMap.get(skuId);
                if (!activities.isEmpty()) {
                    skuDto.setActivityList(activities);
                }

                // 设置优惠券列表
                List<Coupon> coupons = skuCouponsMap.get(skuId);
                if (!coupons.isEmpty()) {
                    skuDto.setCouponList(coupons);
                }

                skuList.add(skuDto);
            }

            categoryDto.setSkus(skuList);

            // 设置分页信息
            List<PageVo> pagination = new ArrayList<>();
            PageVo pageVo = new PageVo();
            pageVo.setTotal((long) skuList.size());
            pageVo.setPageNum(request.getPagination() != null ? request.getPagination().getPageNum().longValue() : 1L);
            pageVo.setPageSize(
                    request.getPagination() != null ? request.getPagination().getPageSize().longValue() : 8L);
            pagination.add(pageVo);
            categoryDto.setPagination(pagination);

            result.add(categoryDto);
        }

        return result;
    }
}
